<template>
  <div class="Login">
    <h2>登录</h2>
    <!-- 表单 -->
    <el-form
      class="reForm"
      label-position="top"
      label-width="80px"
      :model="User"
      :rules="rules"
      hide-required-asterisk
    >
      <!--  去登录页面 -->
      <a href="javascript:;" class="goRegister iconfont" @click="goRegister"
        >注册&#xe60d;</a
      >
      <el-form-item label="" prop="uname">
        <label for="tel" class="lab"> 账号：</label>
        <el-input
          v-model="User.uname"
          class="inp"
          placeholder="请输入账号"
        ></el-input>
      </el-form-item>
      <el-form-item prop="pass">
        <label for="tel" class="lab">密码：</label>
        <el-input
          class="inp"
          type="password"
          show-password
          v-model="User.pass"
          placeholder="请输入密码"
        ></el-input>
      </el-form-item>
      <!-- 登录 -->
      <div class="go">
        <el-button type="success" class="goLogin" @click="goMain"
          >登录</el-button
        >
      </div>
    </el-form>
  </div>
</template>

<script>
  import { postLogin } from '@/api/login.js';
  export default {
    name: 'Login',
    data() {
      return {
        User: {
          uname: '', //账号
          pass: '',
        },
        rules: {
          uname: [{ required: true, message: '请输入账号', trigger: 'blur' }],
          pass: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        },
        token: '',
      };
    },
    // 数据 监听器
    watch: {
      token(newToken, oblToken) {
        // 把token 传给 vuex
        this.$store.commit('getToken', newToken);
      },
      methods: {
        //  跳转 注册
        goRegister() {
          this.$router.push('/register');
        },
        //  登录
        async goMain() {
          const { data: res } = await postLogin('/login', this.User);
          // 如果 res 有值
          if (res) {
            //   如果有token值
            if (res.data) {
              //  存储 token
              localStorage.setItem('token', res.data);
              this.$router.push('/main');
            }
          }
        },
        //  获取本地token 存在 vuex里面
        getToken() {
          this.token = localStorage.getItem('token');
          // 把token 传给 vuex
          this.$store.commit('getToken', this.token);
          console.log(this.token);
        },
      },
      created() {
        //  调用 获取token
        this.getToken();
      },
    },
  };
</script>

<style lang="less" scoped>
  @import url('../state/css/LoginRegister/Login.less');
</style>
